package com.formula.datastructure.exercise.tree;

public class BinaryLinkNode {
    public Integer data;

    public BinaryLinkNode left;
    public BinaryLinkNode right;

    public int layer = 1;

    public BinaryLinkNode(Integer data) {
        this.data = data;
    }

    public int getDepth() {
        int a = 0;
        int b = 0;
        if (left != null) {
            a = left.getDepth();
        }
        if (right != null) {
            b = right.getDepth();
        }

        return 1 + (a > b ? a : b);
    }

    public void inOrder() {
        if (left != null) {
            left.inOrder();
        }
        visit();
        if (right != null) {
            right.inOrder();
        }
    }


    public int getLeafNum() {
        if (left == null && right == null) {
            return 1;
        }

        int a = 0;
        int b = 0;

        if (left != null) {
            a = left.getLeafNum();
        }
        if (right != null) {
            b = right.getLeafNum();
        }
        return a + b;
    }

    public int singleChild() {
        if (left == null && right == null) {
            return 0;
        }
        if (left != null && right == null) {
            return left.singleChild() + 1;
        }
        if (right != null && left == null) {
            return right.singleChild() + 1;
        }

        return left.singleChild() + right.singleChild();
    }

    public int bothChilds() {
        int result = 0;
        int a;
        int b;
        if (left != null && right != null) {
            a = left.bothChilds();
            b = right.bothChilds();
            result = 1 + a + b;
        } else {
            if (left != null) {
                result = left.bothChilds();
            }
            if (right != null) {
                result = right.bothChilds();
            }
        }
        return result;
    }

    public BinaryLinkNode search(Integer value) {
        if (data == value) {
            return this;
        }
        BinaryLinkNode result = null;
        if (left != null) {
            result = left.search(value);
        }
        if (result == null && right != null) {
            result = right.search(value);
        }
        return result;
    }

    private void visit() {
        System.out.println(data);
    }

}
